import { _decorator, Component, Node, TiledMap, input, Input, EventMouse, EventTouch, Vec3, Vec2, math, Camera, UITransform, Label, Color, tween } from 'cc';
import { MapLayersType } from 'db://assets/battle/Enums';
import { LOG } from '../../../ConsoleLogCtrl';
const { ccclass, property } = _decorator;

/**
 * TiledMap交互控制器
 * 专门为TiledMap物体实现鼠标悬停滚轮缩放和长按拖拽移动功能
 */
@ccclass('MapController')
export class MapController extends Component {
    @property(TiledMap)
    public tiledMap: TiledMap = null;
    
    @property(Camera)
    public camera: Camera = null;
    
    @property({ tooltip: '缩放速度' })
    public zoomSpeed: number = 0.05;
    
    @property({ tooltip: '最小缩放比例' })
    public minZoom: number = 1;
    
    @property({ tooltip: '最大缩放比例' })
    public maxZoom: number = 5.0;
    
    @property({ tooltip: '拖拽速度' })
    public dragSpeed: number = 1;
    
    @property({ tooltip: '是否只在鼠标悬停在TiledMap上时响应' })
    public onlyOnHover: boolean = true;
    
    // 私有变量
    private _isDragging: boolean = false;
    private _isMouseDown: boolean = false;
    private _lastMousePosition: Vec2 = new Vec2();
    private _mouseDownPosition: Vec2 = new Vec2();
    private _currentZoom: number = 1.0;
    private _isMouseOverMap: boolean = false;
    private _originalMapScale: Vec3 = new Vec3(1, 1, 1);
    
    /**
     * 组件启动时初始化
     */
    onLoad() {
        // 如果没有指定TiledMap，尝试获取当前节点的TiledMap组件
        if (!this.tiledMap) {
            this.tiledMap = this.node.getComponent(TiledMap);
        }
        
        // 如果没有指定相机，尝试查找场景中的主相机
        if (!this.camera) {
            const cameraNode = this.node.scene.getChildByName('Main Camera');
            if (cameraNode) {
                this.camera = cameraNode.getComponent(Camera);
            }
        }
        
        if (!this.tiledMap) {
            LOG.error('MapController: 未找到TiledMap组件');
            return;
        }
        
        // 保存原始缩放
        this._originalMapScale.set(this.tiledMap.node.scale);
        
        this.registerInputEvents();
    }
    
    /**
     * 注册输入事件
     */
    private registerInputEvents() {
        // 注册鼠标滚轮事件
        input.on(Input.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
        
        // 注册鼠标移动事件（用于检测悬停）
        input.on(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
        
        // 注册鼠标按下事件
        input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
        
        // 注册鼠标抬起事件
        input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
        
        // 注册触摸事件（移动端支持）
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }
    
    /**
     * 组件销毁时取消事件监听
     */
    onDestroy() {
        input.off(Input.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
        input.off(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
        input.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
        input.off(Input.EventType.MOUSE_UP, this.onMouseUp, this);
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }
    
    /**
     * 检查鼠标是否在TiledMap上
     * @param screenPos 屏幕坐标
     * @returns 是否在TiledMap上
     */
    private isMouseOverTiledMap(screenPos: Vec2): boolean {
        if (!this.tiledMap || !this.camera) return false;
        
        // 将屏幕坐标转换为世界坐标
        const worldPos = new Vec3();
        this.camera.screenToWorld(new Vec3(screenPos.x, screenPos.y, 0), worldPos);
        
        // 获取TiledMap的边界框
        const mapNode = this.tiledMap.node;
        const uitransform = this.tiledMap.getComponent(UITransform);
        const mapSize = this.tiledMap.getMapSize();
        const tileSize = this.tiledMap.getTileSize();
        
        // 计算地图在世界坐标中的边界
        const mapWorldPos = mapNode.worldPosition;
        const mapScale = mapNode.worldScale;
        
        const mapWidth = mapSize.width * tileSize.width * mapScale.x;
        const mapHeight = mapSize.height * tileSize.height * mapScale.y;
        
        const minX = mapWorldPos.x - mapWidth * uitransform.anchorX;
        const maxX = minX + mapWidth;
        const minY = mapWorldPos.y - mapHeight * uitransform.anchorY;
        const maxY = minY + mapHeight;
        
        return worldPos.x >= minX && worldPos.x <= maxX && worldPos.y >= minY && worldPos.y <= maxY;
    }
    
    /**
     * 处理鼠标移动事件（检测悬停和拖拽）
     * @param event 鼠标事件
     */
    private onMouseMove(event: EventMouse) {
        const currentPosition = new Vec2(event.getLocationX(), event.getLocationY());
        
        // 更新悬停状态
        this._isMouseOverMap = this.isMouseOverTiledMap(currentPosition);
        
        // 如果鼠标按下且在地图上（或不限制悬停），开始拖拽
        if (this._isMouseDown && !this._isDragging) {
            if (!this.onlyOnHover || this._isMouseOverMap) {
                this._isDragging = true;
                LOG.log('MapController: 开始拖拽TiledMap');
            }
        }
        
        // 如果正在拖拽，更新地图位置
        if (this._isDragging) {
            this.updateMapPosition(currentPosition);
        }
        
        this._lastMousePosition.set(currentPosition.x, currentPosition.y);
    }
    
    /**
     * 处理鼠标滚轮事件
     * @param event 鼠标事件
     */
    private onMouseWheel(event: EventMouse) {
        if (!this.tiledMap) return;
        
        // 如果启用了悬停检测，只有鼠标在地图上时才响应
        if (this.onlyOnHover && !this._isMouseOverMap) {
            return;
        }
        
        // 获取滚轮滚动方向
        const scrollY = event.getScrollY() > 0 ? 1 : -1;
        
        // 计算缩放变化
        const zoomDelta = scrollY * this.zoomSpeed;
        const newZoom = math.clamp(this._currentZoom + zoomDelta, this.minZoom, this.maxZoom);
        
        // 应用缩放
        this.applyZoom(newZoom, new Vec2(event.getLocationX(), event.getLocationY()));
    }
    
    /**
     * 处理鼠标按下事件
     * @param event 鼠标事件
     */
    private onMouseDown(event: EventMouse) {
        // 记录鼠标按下状态和位置
        this._isMouseDown = true;
        this._mouseDownPosition.set(event.getLocationX(), event.getLocationY());
        this._lastMousePosition.set(event.getLocationX(), event.getLocationY());
        
        // 更新悬停状态
        this._isMouseOverMap = this.isMouseOverTiledMap(this._mouseDownPosition);
    }
    
    /**
     * 处理鼠标抬起事件
     * @param event 鼠标事件
     */
    private onMouseUp(event: EventMouse) {
        const clickPosition = new Vec2(event.getLocationX(), event.getLocationY());
        if(!this._isDragging){
            this.checkTileAtPosition(clickPosition);
        }
        
        this._isMouseDown = false;
        this._isDragging = false;
    }
    
    /**
     * 检查指定屏幕位置的瓦片坐标
     * @param screenPos 屏幕坐标
     */
    private checkTileAtPosition(screenPos: Vec2): void {
        if (!this.tiledMap || !this.camera) {
            LOG.error('MapController: TiledMap或Camera未找到');
            return;
        }
        
        // 获取地图信息
        const mapSize = this.tiledMap.getMapSize();
        const tileSize = this.tiledMap.getTileSize();
        const layer = this.tiledMap.getLayer(MapLayersType.plain);
        
        if (!layer) {
            LOG.error('MapController: 地图图层未找到');
            return;
        }

        // 1. 屏幕坐标转世界坐标
        const worldPos = new Vec3();
        this.camera.screenToWorld(new Vec3(screenPos.x, screenPos.y, 0), worldPos);
        
        // 2. 世界坐标转地图节点本地坐标
        const mapTransform = this.tiledMap.getComponent(UITransform);
        if (!mapTransform) {
            LOG.error('MapController: 地图UITransform组件未找到');
            return;
        }
        
        const localPos = new Vec3();
        mapTransform.convertToNodeSpaceAR(worldPos, localPos);
        
        // 3. 获取地图像素尺寸和锚点信息
        const mapPixelWidth = mapSize.width * tileSize.width;
        const mapPixelHeight = mapSize.height * tileSize.height;
        
        // 4. 调整本地坐标（考虑锚点）
        const adjustedLocalPos = new Vec2();
        adjustedLocalPos.x = localPos.x + mapPixelWidth * mapTransform.anchorX;
        adjustedLocalPos.y = localPos.y + mapPixelHeight * mapTransform.anchorY;
        
        // 5. Y轴翻转（Cocos Creator的Y轴向上为正，瓦片地图Y轴向下为正）
        adjustedLocalPos.y = mapPixelHeight - adjustedLocalPos.y;
        
        // 6. 计算瓦片坐标
        const tileX_float = adjustedLocalPos.x / tileSize.width;
        const tileY_float = adjustedLocalPos.y / tileSize.height;
        
        // 7. 转换为整数坐标并限制范围
        const tileX = Math.max(0, Math.min(mapSize.width - 1, Math.floor(tileX_float)));
        const tileY = Math.max(0, Math.min(mapSize.height - 1, Math.floor(tileY_float)));
        
        // 8. 输出调试信息
        //LOG.warn(`MapController: 最终瓦片坐标: (${tileX}, ${tileY})`);
        
        // 9. 检查坐标是否在有效范围内
        if (tileX >= 0 && tileX < mapSize.width && tileY >= 0 && tileY < mapSize.height) {
            //显示坐标飘字
            this.showTilePosition(tileX, tileY);
        }
    }
    
    /**
     * 显示坐标飘字
     * 显示0.5秒后自动删除
     * @param tileX 瓦片X坐标
     * @param tileY 瓦片Y坐标
     */
    private showTilePosition(tileX: number, tileY: number): void {
        if (!this.tiledMap) {
            LOG.warn('MapController: TiledMap未找到，无法显示飘字');
            return;
        }

        // 1. 计算瓦片在地图中的像素位置
        const tileSize = this.tiledMap.getTileSize();
        const mapSize = this.tiledMap.getMapSize();
        
        // 瓦片中心位置（像素坐标）
        const tilePixelX = (tileX + 0.5) * tileSize.width;
        const tilePixelY = (mapSize.height - tileY - 0.5) * tileSize.height; // Y轴翻转
        
        // 2. 转换为地图节点的本地坐标
        const mapTransform = this.tiledMap.getComponent(UITransform);
        if (!mapTransform) {
            LOG.warn('MapController: 地图UITransform组件未找到');
            return;
        }
        
        // 计算地图像素尺寸
        const mapPixelWidth = mapSize.width * tileSize.width;
        const mapPixelHeight = mapSize.height * tileSize.height;
        
        // 考虑锚点的本地坐标
        const localX = tilePixelX - mapPixelWidth * mapTransform.anchorX;
        const localY = tilePixelY - mapPixelHeight * mapTransform.anchorY;
        
        // 3. 创建飘字节点
        const floatingTextNode = new Node('FloatingText');
        
        // 添加Label组件
        const label = floatingTextNode.addComponent(Label);
        label.string = `(${tileX}, ${tileY})`;
        label.fontSize = 16;
        label.color = new Color(255, 255, 255, 255); // 白色文字
        
        // 添加UITransform组件
        const textTransform = floatingTextNode.addComponent(UITransform);
        textTransform.setContentSize(80, 24);
        textTransform.setAnchorPoint(0.5, 0.5);
        
        // 4. 设置初始位置（瓦片中心位置）
        floatingTextNode.setPosition(localX, localY, 0);
        
        // 5. 添加到地图节点
        this.tiledMap.node.addChild(floatingTextNode);
        
        // 6. 创建飘字动画
        const startPos = floatingTextNode.position.clone();
        const targetPos = startPos.clone();
        targetPos.y += 30; // 向上飘动30像素
        
        // 创建颜色渐变（淡出效果）
        const fadeColor = label.color.clone();
        fadeColor.a = 0; // 完全透明
        
        // 执行动画：向上移动 + 淡出
        tween(floatingTextNode)
            .parallel(
                // 位置动画：向上飘动
                tween(floatingTextNode).to(0.5, { position: targetPos }, { easing: 'sineOut' }),
                // 透明度动画：延迟0.2秒后开始淡出
                tween(label).delay(0.2).to(0.3, { color: fadeColor }, { easing: 'sineIn' })
            )
            .call(() => {
                // 动画完成后销毁飘字节点
                if (floatingTextNode && floatingTextNode.isValid) {
                    floatingTextNode.destroy();
                }
                LOG.log(`MapController: 飘字动画完成，坐标: (${tileX}, ${tileY})`);
            })
            .start();
            
        LOG.log(`MapController: 显示飘字 - 瓦片坐标: (${tileX}, ${tileY}), 本地坐标: (${localX.toFixed(2)}, ${localY.toFixed(2)})`);
    }

    
    /**
     * 处理触摸开始事件（移动端）
     * @param event 触摸事件
     */
    private onTouchStart(event: EventTouch) {
        const touch = event.touch;
        this._isMouseDown = true;
        this._mouseDownPosition.set(touch.getLocationX(), touch.getLocationY());
        this._lastMousePosition.set(touch.getLocationX(), touch.getLocationY());
        
        // 更新悬停状态
        this._isMouseOverMap = this.isMouseOverTiledMap(this._mouseDownPosition);
    }
    
    /**
     * 处理触摸移动事件（移动端）
     * @param event 触摸事件
     */
    private onTouchMove(event: EventTouch) {
        const touch = event.touch;
        const currentPosition = new Vec2(touch.getLocationX(), touch.getLocationY());
        
        // 如果触摸按下且在地图上（或不限制悬停），开始拖拽
        if (this._isMouseDown && !this._isDragging) {
            if (!this.onlyOnHover || this._isMouseOverMap) {
                this._isDragging = true;
                LOG.log('MapController: 开始触摸拖拽TiledMap');
            }
        }
        
        if (this._isDragging) {
            this.updateMapPosition(currentPosition);
        }
        
        this._lastMousePosition.set(currentPosition.x, currentPosition.y);
    }
    
    /**
     * 处理触摸结束事件（移动端）
     * @param event 触摸事件
     */
    private onTouchEnd(event: EventTouch) {
        if (this._isDragging) {
            LOG.log('MapController: 结束触摸拖拽TiledMap');
        }
        this._isMouseDown = false;
        this._isDragging = false;
    }
    
    /**
     * 应用缩放到TiledMap
     * @param newZoom 新的缩放值
     * @param centerPoint 缩放中心点（屏幕坐标）
     */
    private applyZoom(newZoom: number, centerPoint?: Vec2) {
        if (!this.tiledMap) return;
        
        const oldZoom = this._currentZoom;
        this._currentZoom = newZoom;
        
        // 计算新的缩放比例
        const scaleRatio = this._currentZoom;
        const newScale = new Vec3(
            this._originalMapScale.x * scaleRatio,
            this._originalMapScale.y * scaleRatio,
            this._originalMapScale.z * scaleRatio
        );
        
        // 如果提供了缩放中心点，调整地图位置以保持中心点不变
        if (centerPoint && this.camera) {
            const mapNode = this.tiledMap.node;
            const oldWorldPos = new Vec3();
            this.camera.screenToWorld(new Vec3(centerPoint.x, centerPoint.y, 0), oldWorldPos);
            
            // 应用缩放
            mapNode.setScale(newScale);
            
            // 计算缩放后的世界坐标
            const newWorldPos = new Vec3();
            this.camera.screenToWorld(new Vec3(centerPoint.x, centerPoint.y, 0), newWorldPos);
            
            // 调整地图位置
            const offset = oldWorldPos.subtract(newWorldPos);
            const newPosition = mapNode.position.add(offset);
            
            // 应用边界限制
            const clampedPos = this.clampMapPosition(newPosition);
            mapNode.setPosition(clampedPos);
        } else {
            // 直接应用缩放
            this.tiledMap.node.setScale(newScale);
            
            // 缩放后也需要检查边界限制
            const currentPos = this.tiledMap.node.position;
            const clampedPos = this.clampMapPosition(currentPos);
            this.tiledMap.node.setPosition(clampedPos);
        }
        
        LOG.log(`MapController: TiledMap缩放更新: ${this._currentZoom.toFixed(2)}`);
    }
    
    /**
     * 更新地图位置
     * @param currentPosition 当前鼠标/触摸位置
     */
    private updateMapPosition(currentPosition: Vec2) {
        if (!this.tiledMap || !this.camera) return;
        
        // 计算屏幕坐标差值
        const deltaX = currentPosition.x - this._lastMousePosition.x;
        const deltaY = currentPosition.y - this._lastMousePosition.y;
        
        // 将当前位置和上一个位置都转换为世界坐标
        const currentWorldPos = new Vec3();
        const lastWorldPos = new Vec3();
        
        this.camera.screenToWorld(new Vec3(currentPosition.x, currentPosition.y, 0), currentWorldPos);
        this.camera.screenToWorld(new Vec3(this._lastMousePosition.x, this._lastMousePosition.y, 0), lastWorldPos);
        
        // 计算世界坐标差值
        const worldDeltaX = currentWorldPos.x - lastWorldPos.x;
        const worldDeltaY = currentWorldPos.y - lastWorldPos.y;
        
        // 获取当前地图位置
        const currentPos = this.tiledMap.node.position;
        
        // 计算新位置（使用世界坐标差值，考虑拖拽速度）
        const newPos = new Vec3(
            currentPos.x + worldDeltaX * this.dragSpeed,
            currentPos.y + worldDeltaY * this.dragSpeed,
            currentPos.z
        );
        
        // 应用边界限制
        const clampedPos = this.clampMapPosition(newPos);
        this.tiledMap.node.setPosition(clampedPos);
    }
    
    /**
     * 限制地图位置在父物体边界内
     * @param position 目标位置
     * @returns 限制后的位置
     */
    private clampMapPosition(position: Vec3): Vec3 {
        if (!this.tiledMap) return position;
        
        const mapNode = this.tiledMap.node;
        const parentNode = mapNode.parent;
        
        if (!parentNode) return position;
        
        // 获取父物体的UITransform组件
        const parentTransform = parentNode.getComponent(UITransform);
        if (!parentTransform) return position;
        
        // 获取地图的UITransform组件
        const mapTransform = mapNode.getComponent(UITransform);
        if (!mapTransform) return position;
        
        // 获取地图和父物体的尺寸
        const mapSize = this.tiledMap.getMapSize();
        const tileSize = this.tiledMap.getTileSize();
        const mapScale = mapNode.scale;
        
        // 计算地图的实际尺寸（考虑缩放）
        const mapWidth = mapSize.width * tileSize.width * mapScale.x;
        const mapHeight = mapSize.height * tileSize.height * mapScale.y;
        
        // 获取父物体的尺寸
        const parentWidth = parentTransform.width;
        const parentHeight = parentTransform.height;
        
        // 计算地图锚点偏移
        const mapAnchorOffsetX = mapWidth * mapTransform.anchorX;
        const mapAnchorOffsetY = mapHeight * mapTransform.anchorY;
        
        // 计算父物体锚点偏移
        const parentAnchorOffsetX = parentWidth * parentTransform.anchorX;
        const parentAnchorOffsetY = parentHeight * parentTransform.anchorY;
        
        // 计算边界限制
        let minX, maxX, minY, maxY;
        
        if (mapWidth <= parentWidth) {
            // 如果地图宽度小于等于父物体宽度，居中显示
            const centerX = parentWidth / 2 - parentAnchorOffsetX;
            minX = maxX = centerX - mapWidth / 2 + mapAnchorOffsetX;
        } else {
            // 如果地图宽度大于父物体宽度，限制边界
            minX = parentWidth - parentAnchorOffsetX - mapWidth + mapAnchorOffsetX;
            maxX = -parentAnchorOffsetX + mapAnchorOffsetX;
        }
        
        if (mapHeight <= parentHeight) {
            // 如果地图高度小于等于父物体高度，居中显示
            const centerY = parentHeight / 2 - parentAnchorOffsetY;
            minY = maxY = centerY - mapHeight / 2 + mapAnchorOffsetY;
        } else {
            // 如果地图高度大于父物体高度，限制边界
            minY = parentHeight - parentAnchorOffsetY - mapHeight + mapAnchorOffsetY;
            maxY = -parentAnchorOffsetY + mapAnchorOffsetY;
        }
        
        // 应用边界限制
        const clampedX = math.clamp(position.x, minX, maxX);
        const clampedY = math.clamp(position.y, minY, maxY);
        
        return new Vec3(clampedX, clampedY, position.z);
    }
    
    /**
     * 重置TiledMap位置和缩放
     */
    public resetMap() {
        if (!this.tiledMap) return;
        
        // 重置缩放
        this.tiledMap.node.setScale(this._originalMapScale);
        this._currentZoom = 1.0;
        
        // 重置位置并应用边界限制
        const resetPos = new Vec3(0, 0, this.tiledMap.node.position.z);
        const clampedPos = this.clampMapPosition(resetPos);
        this.tiledMap.node.setPosition(clampedPos);
        
        LOG.log('MapController: TiledMap已重置');
    }
    
    /**
     * 设置TiledMap位置
     * @param x X坐标
     * @param y Y坐标
     */
    public setMapPosition(x: number, y: number) {
        if (!this.tiledMap) return;
        
        const targetPos = new Vec3(x, y, this.tiledMap.node.position.z);
        const clampedPos = this.clampMapPosition(targetPos);
        this.tiledMap.node.setPosition(clampedPos);
    }
    
    /**
     * 获取当前缩放值
     */
    public getCurrentZoom(): number {
        return this._currentZoom;
    }
    
    /**
     * 设置缩放值
     * @param zoom 缩放值
     */
    public setZoom(zoom: number) {
        const clampedZoom = math.clamp(zoom, this.minZoom, this.maxZoom);
        this.applyZoom(clampedZoom);
    }
    
    /**
     * 启用/禁用悬停检测
     * @param enabled 是否启用
     */
    public setHoverDetectionEnabled(enabled: boolean) {
        this.onlyOnHover = enabled;
    }
    
    /**
     * 获取TiledMap在屏幕上的边界框
     * @returns 边界框信息
     */
    public getMapBounds(): { minX: number, maxX: number, minY: number, maxY: number } {
        if (!this.tiledMap) {
            return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
        }
        
        const mapNode = this.tiledMap.node;
        const uitransform = this.tiledMap.getComponent(UITransform);
        const mapSize = this.tiledMap.getMapSize();
        const tileSize = this.tiledMap.getTileSize();
        
        const mapWorldPos = mapNode.worldPosition;
        const mapScale = mapNode.worldScale;
        
        const mapWidth = mapSize.width * tileSize.width * mapScale.x;
        const mapHeight = mapSize.height * tileSize.height * mapScale.y;
        
        const minX = mapWorldPos.x - mapWidth * uitransform.anchorX;
        const maxX = minX + mapWidth;
        const minY = mapWorldPos.y - mapHeight * uitransform.anchorY;
        const maxY = minY + mapHeight;
        
        return { minX, maxX, minY, maxY };
    }
    
    /**
     * 获取地图在父物体中的移动边界限制
     * @returns 移动边界限制信息
     */
    public getMovementBounds(): { minX: number, maxX: number, minY: number, maxY: number } {
        if (!this.tiledMap) {
            return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
        }
        
        const mapNode = this.tiledMap.node;
        const parentNode = mapNode.parent;
        
        if (!parentNode) {
            return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
        }
        
        // 获取父物体的UITransform组件
        const parentTransform = parentNode.getComponent(UITransform);
        if (!parentTransform) {
            return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
        }
        
        // 获取地图的UITransform组件
        const mapTransform = mapNode.getComponent(UITransform);
        if (!mapTransform) {
            return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
        }
        
        // 获取地图和父物体的尺寸
        const mapSize = this.tiledMap.getMapSize();
        const tileSize = this.tiledMap.getTileSize();
        const mapScale = mapNode.scale;
        
        // 计算地图的实际尺寸（考虑缩放）
        const mapWidth = mapSize.width * tileSize.width * mapScale.x;
        const mapHeight = mapSize.height * tileSize.height * mapScale.y;
        
        // 获取父物体的尺寸
        const parentWidth = parentTransform.width;
        const parentHeight = parentTransform.height;
        
        // 计算地图锚点偏移
        const mapAnchorOffsetX = mapWidth * mapTransform.anchorX;
        const mapAnchorOffsetY = mapHeight * mapTransform.anchorY;
        
        // 计算父物体锚点偏移
        const parentAnchorOffsetX = parentWidth * parentTransform.anchorX;
        const parentAnchorOffsetY = parentHeight * parentTransform.anchorY;
        
        // 计算边界限制
        let minX, maxX, minY, maxY;
        
        if (mapWidth <= parentWidth) {
            // 如果地图宽度小于等于父物体宽度，居中显示
            const centerX = parentWidth / 2 - parentAnchorOffsetX;
            minX = maxX = centerX - mapWidth / 2 + mapAnchorOffsetX;
        } else {
            // 如果地图宽度大于父物体宽度，限制边界
            minX = parentWidth - parentAnchorOffsetX - mapWidth + mapAnchorOffsetX;
            maxX = -parentAnchorOffsetX + mapAnchorOffsetX;
        }
        
        if (mapHeight <= parentHeight) {
            // 如果地图高度小于等于父物体高度，居中显示
            const centerY = parentHeight / 2 - parentAnchorOffsetY;
            minY = maxY = centerY - mapHeight / 2 + mapAnchorOffsetY;
        } else {
            // 如果地图高度大于父物体高度，限制边界
            minY = parentHeight - parentAnchorOffsetY - mapHeight + mapAnchorOffsetY;
            maxY = -parentAnchorOffsetY + mapAnchorOffsetY;
        }
        
        return { minX, maxX, minY, maxY };
    }
}